import type { RouteRecordRaw } from "vue-router"
import { useUserStore } from "./user"
import { asyncRoutes } from "@/router"
import { useMenuStore } from "./menu"
import type { MenuData } from "@/api/menu"
import path from "path-browserify"
/**
 *
 * @param routes 本地异步路由
 * @param  routesPath 远程路由path 组成的数组
 * @param  basePath 是父路径，递归要用
 * @returns
 */
function generateRoutes(
  routes: RouteRecordRaw[],
  routesPath: string[],
  basePath = "/"
) {
  const routerData: RouteRecordRaw[] = []
  routes.forEach((route) => {
    // 由于路由表，父路径==>path:'/dashboard'   子路径==>path:index，要拼接
    const routePath = path.resolve(basePath, route.path)
    if (route.children) {
      route.children = generateRoutes(route.children, routesPath, routePath)
    }
    // 自己匹配我需要将自己放进去，如果儿子匹配成功父亲也要放入
    if (
      routesPath.includes(routePath) ||
      (route.children && route.children.length >= 1)
    ) {
      routerData.push(route)
    }
  })
  return routerData
}
/**
 *
 * @param menus 远程路由
 * @param routes 本地异步路由
 * @returns
 */
function filterAsyncRoutes(menus: MenuData[], routes: RouteRecordRaw[]) {
  const routesPath = menus.map((item) => item.path)

  return generateRoutes(routes, routesPath)
}

export const usePermissionStore = defineStore("permission", () => {
  const userStore = useUserStore()

  const menuStore = useMenuStore()

  // 添加动态的组件
  let accessMenuRoutes: RouteRecordRaw[] = []
  const generateRoutes = async () => {
    // 获取角色类型数组
    const rolesNames = computed(() =>
      userStore.state.roles.map((item) => item.name)
    )

    // 如果，不是超管理员，是其他角色的 id 数组
    const roleIds = computed(() => userStore.state.roles.map((item) => item.id))

    if (rolesNames.value.includes("super_admin")) {
      // 超级管理员，啥都不用干，返回所有路由，把常量路由 + 异步路由
      accessMenuRoutes = asyncRoutes
      // 去生成一个菜单， 根据角色来生成
      await menuStore.getAllMenuListByAdmin()
      return accessMenuRoutes
    } else {
      // 如果，不是超管理员，是其他角色
      await menuStore.getMenuListByRoles(roleIds.value)
      // 筛选所需要加载的路由
      const menus = menuStore.state.authMenuList
      accessMenuRoutes = filterAsyncRoutes(menus, asyncRoutes)
      return accessMenuRoutes
    }
  }
  return {
    generateRoutes
  }
})
